package com.example.RuanJianKeShe.Service.login;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCode")
public class checkCode extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 100;
        int height = 40;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.blue);
        graphics.fillRect(0,0,width,height);
        graphics.setColor(Color.green);
        graphics.drawRect(0,0,width - 1,height - 1);
        String str = "ACDEF2G3HJ4K5MNP6R7STUV9WXYZ";
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for(int i = 0;i<4;i++){
            int index = random.nextInt(str.length());
            char ch = str.charAt(index);
            stringBuffer.append(ch);
            graphics.setFont(new Font("Tahoma", Font.BOLD, 19));
            graphics.drawString(ch+"",width/4*i+10,height*6/10);
        }
        String checkCode_session = stringBuffer.toString();
        req.getSession().setAttribute("checkCode_session",checkCode_session);
        for (int i=0;i<7;i++){
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int x3 = random.nextInt(width);
            int x4 = random.nextInt(width);
            graphics.drawLine(x1,x2,x3,x4);
        }
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
